package com.lufei.message_system.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lufei.message_system.Data.PageResult;
import com.lufei.message_system.Data.Result;
import com.lufei.message_system.Data.User;
import com.lufei.message_system.Data.UserVD.*;
import com.lufei.message_system.Mapper.UserMapper;
import com.lufei.message_system.Service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<UserVO> createUser(UserCreateDTO userDTO) {
        // 验证角色对应的字段是否完整
        if (!userDTO.isValidForRole()) {
            String errorMsg = "当前角色所需信息不完整或用户号格式不正确";
            if ("admin".equals(userDTO.getRole())) {
                errorMsg += "（管理员用户号必须是1-5位数字）";
            } else if ("teacher".equals(userDTO.getRole())) {
                errorMsg += "（教师用户号必须是6-9位数字）";
            } else {
                errorMsg += "（学生用户号必须是至少10位数字）";
            }
            return Result.error(errorMsg);
        }

        // 检查学号是否已存在
        User existingUser = userMapper.selectById(userDTO.getUserId());
        if (existingUser != null) {
            return Result.error("用户号已存在");
        }

        // DTO转Entity
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setCreateTime(new Date());

        // 保存到数据库
        int result = userMapper.insert(user);
        if (result <= 0) {
            return Result.error("创建用户失败");
        }

        // 返回结果
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return Result.success(userVO);
    }

    @Override
    public Result<UserVO> getUser(String userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return Result.success(userVO);
    }

    @Override
    public Result<UserVO> updateUser(String userId, UserUpdateDTO userDTO) {
        // 检查用户是否存在
        User existingUser = userMapper.selectById(userId);
        if (existingUser == null) {
            return Result.error("用户不存在");
        }

        // 更新用户信息
        BeanUtils.copyProperties(userDTO, existingUser);
        int result = userMapper.updateById(existingUser);
        if (result <= 0) {
            return Result.error("更新用户失败");
        }

        // 返回更新后的用户信息
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(existingUser, userVO);
        return Result.success(userVO);
    }

    @Override
    public Result deleteUser(String userId) {
        int result = userMapper.deleteById(userId);
        if (result <= 0) {
            return Result.error("删除用户失败");
        }
        return Result.success();
    }

    //用户登录
    @Override
    public Result<UserVO> checklogin(UserLoginDTO loginDTO) {
        // 1. 验证用户号格式是否符合角色要求
        if (!isUserIdValidForRole(loginDTO.getUserId(), loginDTO.getRole())) {
            String errorMsg = "用户号格式不正确";
            if ("admin".equals(loginDTO.getRole())) {
                errorMsg += "（管理员用户号必须是1-5位数字）";
            } else if ("teacher".equals(loginDTO.getRole())) {
                errorMsg += "（教师用户号必须是6-9位数字）";
            } else {
                errorMsg += "（学生用户号必须是至少10位数字）";
            }
            return Result.error(errorMsg);
        }

        // 2. 检查用户是否存在
        User user = userMapper.selectById(loginDTO.getUserId());
        if (user == null) {
            return Result.error("用户号不存在");
        }

        // 3. 验证角色是否匹配
        if (!loginDTO.getRole().equals(user.getRole())) {
            return Result.error("用户角色不匹配");
        }

        // 4. 验证密码
        if (!loginDTO.getPassword().equals(user.getPassword())) {
            return Result.error("密码错误");
        }

        // 5. 登录成功，返回用户信息
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return Result.success(userVO);
    }

    private boolean isUserIdValidForRole(String userId, String role) {
        if (userId == null || !userId.matches("\\d+")) {
            return false;
        }

        int length = userId.length();
        switch (role) {
            case "admin":
                return length >= 1 && length <= 5;
            case "teacher":
                return length >= 6 && length <= 9;
            case "student":
                return length >= 10;
            default:
                return false;
        }
    }

    @Override
    public Result<PageResult<UserVO>> listUsers(Integer page, Integer size, UserQueryDTO queryDTO) {
        // 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        
        // 添加用户号查询条件
        if (StringUtils.hasText(queryDTO.getUserId())) {
            queryWrapper.eq("user_id", queryDTO.getUserId());
        }
        
        if (queryDTO.getCollegeName() != null) {
            queryWrapper.eq("college_name", queryDTO.getCollegeName());
        }
        if (queryDTO.getMajorName() != null) {
            queryWrapper.eq("major_name", queryDTO.getMajorName());
        }
        if (queryDTO.getClassId() != null) {
            queryWrapper.eq("class_id", queryDTO.getClassId());
        }
        if (StringUtils.hasText(queryDTO.getName())) {
            queryWrapper.like("name", queryDTO.getName());
        }
        if (StringUtils.hasText(queryDTO.getRole())) {
            queryWrapper.eq("role", queryDTO.getRole());
        }
        if (StringUtils.hasText(queryDTO.getGrade())) {
            queryWrapper.eq("grade", queryDTO.getGrade());
        }

        // 创建分页对象，确保页码从1开始
        page = Math.max(1, page);
        size = Math.max(1, Math.min(size, 50)); // 限制每页最大条数为50
        Page<User> pageParam = new Page<>(page, size);
        
        // 执行分页查询
        IPage<User> userPage = userMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为VO对象
        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());

        // 构建分页结果
        PageResult<UserVO> pageResult = new PageResult<>();
        pageResult.setList(userVOList);
        pageResult.setTotal(userPage.getTotal());
        pageResult.setPage((int)userPage.getCurrent());
        pageResult.setSize((int)userPage.getSize());

        return Result.success(pageResult);
    }

    @Override
    public Result<PageResult<UserVO>> listUsersByTeacherId(String userId, Integer page, Integer size) {
        // 1. 先获取用户信息
        User teacher = userMapper.selectById(userId);
        if (teacher == null) {
            return Result.error("用户不存在");
        }

        // 2. 验证是否为教师角色
        if (!"teacher".equals(teacher.getRole())) {
            return Result.error("该用户不是教师");
        }

        // 3. 检查教师是否有带班级信息
        if (teacher.getClassId() == null || teacher.getGrade() == null ||
                teacher.getUniversityName() == null || teacher.getCollegeName() == null ||
                teacher.getMajorName() == null) {
            return Result.error("该教师没有完整的班级信息");
        }

        // 4. 查询该班级所有学生（精确匹配教师所带班级）
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("university_name", teacher.getUniversityName())
                .eq("college_name", teacher.getCollegeName())
                .eq("major_name", teacher.getMajorName())
                .eq("grade", teacher.getGrade())
                .eq("class_id", teacher.getClassId())
                .eq("role", "student"); // 只查询学生

        // 创建分页对象，确保页码从1开始
        page = Math.max(1, page);
        size = Math.max(1, Math.min(size, 50)); // 限制每页最大条数为50
        Page<User> pageParam = new Page<>(page, size);
        
        // 执行分页查询
        IPage<User> userPage = userMapper.selectPage(pageParam, queryWrapper);

        // 转换为VO列表，并确保返回的数据不超过页面大小
        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());

        // 构建分页结果
        PageResult<UserVO> pageResult = new PageResult<>();
        pageResult.setList(userVOList);
        pageResult.setTotal(userPage.getTotal());
        pageResult.setPage((int)userPage.getCurrent());
        pageResult.setSize((int)userPage.getSize());

        return Result.success(pageResult);
    }

    @Override
    public Result resetPassword(String userId, PasswordResetDTO resetDTO) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 验证旧密码
        if (!resetDTO.getOldPassword().equals(user.getPassword())) {
            return Result.error("旧密码不正确");
        }

        // 更新密码
        user.setPassword(resetDTO.getNewPassword());
        int result = userMapper.updateById(user);
        if (result <= 0) {
            return Result.error("密码重置失败");
        }
        return Result.success("密码重置成功");
    }
}